package 三数之和;

import java.util.*;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0;i < nums.length - 2;i++){
            int left = i + 1;
            int right = nums.length - 1;
            int target = -nums[i];
            while (left < right){
                List<Integer> list = new ArrayList<>();
                if (nums[left] + nums[right] > target){
                    right--;
                }else if (nums[left] + nums[right] < target){
                    left++;
                }else {
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    ret.add(list);
                    while (left < right && nums[left + 1] == nums[left]){
                        left++;
                    }
                    left++;
                    while (left < right && nums[right - 1] == nums[right]){
                        right--;
                    }
                    right--;
                }
            }
            while (i < nums.length - 2 && nums[i + 1] == nums[i]){
                i++;
            }
        }
        return ret;
    }
}